package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.*;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.SettingVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.*;

@Component
public class SettingManager {

    @DubboReference
    QuestionService questionService;

    @DubboReference
    NotificationService notificationService;

    @DubboReference
    BlackListService blackListService;

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    //查询用户通知设置
    public ResponseEntity findSetting() {
        //1.获取当前用户
        User user = UserHolder.get();

        //2.远程调用service查询问题
        Question question = questionService.findByUserId(user.getId());
        //3.远程调用service查询通知设置
        Notification notification = notificationService.findByUserId(user.getId());

        //4.封装vo对象且返回
        SettingVo vo = new SettingVo();

        vo.setId(user.getId());
        vo.setPhone(user.getMobile());

        //设置陌生人问题
        if (question != null) {
            vo.setStrangerQuestion(question.getStrangerQuestion());
        }

        //设置 通知设置
        if (notification != null) {
            vo.setPinglunNotification(notification.getPinglunNotification());
            vo.setLikeNotification(notification.getLikeNotification());
            vo.setGonggaoNotification(notification.getGonggaoNotification());
        }

        return ResponseEntity.ok(vo);
    }

    public void setQuestion(String content) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.通过用户id查询陌生人问题
        Question question = questionService.findByUserId(userId);

        //3.判断问题对象是否为空
        if (question == null) {
            //3.1 若为空,则保存
            question = new Question();
            //完善question对象
            question.setStrangerQuestion(content);
            question.setUserId(userId);
            questionService.save(question);
        }else{
            //3.2 否则则修改
            question.setStrangerQuestion(content);
            questionService.update(question);
        }
    }

    public void setNotification(Notification param) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.根据用户id查询用户的通知设置
        Notification notification= notificationService.findByUserId(userId);

        //3.判断通知对象是否为空
        if (notification == null) {
            //3.1 若为空,则保存
            param.setUserId(userId);
            notificationService.save(param);
        }else {
            //3.2 否则则修改
            param.setId(notification.getId());
            notificationService.update(param);
        }
    }

    public ResponseEntity findBlackListByPage(Integer pageNum, Integer pageSize) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.调用service分页查询,返回pageBeanVo(集合中的黑名单只用用户id)
        PageBeanVo vo = blackListService.findByPage(pageNum, pageSize, userId);

        //3.获取分页对象中的集合,获取每个黑名单对象,调用userInfoService查询黑名单用户信息,将userInfo放入一个新集合中
        //3.0 创建一个集合 用来存放黑名单用户信息
        List<UserInfo> userInfos = new ArrayList<>();

        //3.1 获取分页对象中的集合,遍历获取每个黑名单对象
        List<BlackList> items = (List<BlackList>) vo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            items.forEach(e->{
                //3.2 调用userInfoService查询黑名单用户信息
                Long id = e.getBlackUserId();
                UserInfo userInfo = userInfoService.findByUserId(id);

                //3.3 将userInfo放入一个新集合中
                userInfos.add(userInfo);
            });
        }

        //4.将新集合设置给pageBeanVo对象,且返回
        vo.setItems(userInfos);
        return ResponseEntity.ok(vo);
    }

    public void deleteBlackList(Long blackId) {
        //1.获取当前用户id
        //2.调用service删除黑名单
        blackListService.delete(UserHolder.get().getId(),blackId);
    }

    //修改用户手机号码--发验证码
    public void sendCode() {
        //1，获取用户手机号
        String phone = UserHolder.get().getMobile();

        //2，生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);
        //TODO:上线后删除，此时自己方便测试
        code="123456";

        //3，将验证码保存到redis中，时效为5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+phone,code, Duration.ofMinutes(5));
    }

    //修改用户手机号--校验验证码
    public Map checkVerificationCode(Map<String, String> map) {
        //1,获取用户手机号码
        String phone = UserHolder.get().getMobile();

        //2，根据手机号码在redis读取出验证码
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        //3，接收用户输入的验证码
        String verificationCode = map.get("verificationCode");
        Map<String, Boolean> resultMap = new HashMap<>();
        //Map<String,Boolean> verification=new HashMap<>();
        //4，判断验证码是否和redis中保存验证码，若不存在，返回500
        if (!StrUtil.equals(verificationCode,redisCode)){
            resultMap.put("verification",false);
            return resultMap;
        }

        resultMap.put("verification",true);
        //5，删除redis中的验证码
          stringRedisTemplate.delete(ConstantUtil.SMS_CODE+phone);
        return resultMap;
    }

    //修改用户手机号--保存新手机号码
    public ResponseEntity changePhone(Map<String, String> map) {
        //1，获取用户id
        User user = UserHolder.get();

        //2，获取用户输入的新手机号码
        String phone = map.get("phone");

        if (Objects.equals(phone,user.getMobile())){
            //手机号码已存在，返回手机号码已注册
            return ResponseEntity.status(500).body("手机号与原来的相同");
        }

        //3，通过手机号码查询用户，判断是否存在
        User dbUser = userService.findByMobile(phone,user.getId());
        if (dbUser !=null){
            //手机号码已存在，返回手机号码已注册
            return ResponseEntity.status(500).body(ErrorResult.mobileError());
        }else {
            //手机号码不存在，修改用户手机号码
            user.setMobile(phone);
            //4，远程调用service完成修改手机号码操作
            userService.updatePhone(user);
            return ResponseEntity.ok(null);
        }

    }
}
